package cn.hyh.core.component;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther :hyh
 * @desc :   重写auth  拦截器  放开对Option 的请求。
 * @date :2019/8/2
 */
public class MyUserFilter extends UserFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
//        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
////            setHeader(httpRequest,httpResponse);
//            //防止乱码，适用于传输JSON数据
//            httpResponse.setHeader("Content-Type","application/json;charset=UTF-8");
//            httpResponse.setStatus(HttpStatus.OK.value());
//            return true;
//        }
        return super.preHandle(request,response);
    }

    /**
     * 验证失败后调用，但是前后端分离   后台不控制页面的跳转，所以返回状态码 让前端进行跳转。
     * @param request
     * @param response
     * @throws IOException
     */
    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        saveRequest(request);
        Map<String, String> map = new HashMap<>();
        map.put("code", "-2");
        map.put("result", "请先登录!");
        String s = JSON.toJSONString(map);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.close();
//        super.saveRequestAndRedirectToLogin(request, response);
    }
}
